﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyApp.Utils
{
  public class JsonUtils
  {
    public static T GetObjTranNull<T>(Object obj)
    {
      try
      {
        if ((obj == null || obj == DBNull.Value) && (typeof(T) == typeof(string)))
        {
          return (T)Convert.ChangeType("", typeof(T));
        }
        if (obj is T)
        {
          return (T)obj;
        }
        if (typeof(T).IsGenericType)
        {
          Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
          if (genericTypeDefinition == typeof(Nullable<>))
          {
            return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(typeof(T)));
          }
        }
        return (T)Convert.ChangeType(obj, typeof(T));
      }
      catch (InvalidCastException se)
      {
        try
        {
          if (obj != null)
          {
            return (T)obj;
          }
        }
        catch (Exception xe)
        {
        }
      }
      catch (Exception se)
      {

      }

      return default(T);
    }
    public static T JsonDeserialize<T>(string jsonString)
    {
      if (string.IsNullOrEmpty(jsonString))
        return GetObjTranNull<T>(null);
      else
      {
        JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
        {
          NullValueHandling = NullValueHandling.Ignore,
          DefaultValueHandling = DefaultValueHandling.Ignore
        };
        return JsonConvert.DeserializeObject<T>(jsonString, jsonSerializerSettings);
      }
    }
    public static string JsonSerializer(object jsonObject)
    {
      return JsonConvert.SerializeObject(jsonObject,
        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    }
  }
}
